package com.jzy.gulimall.order.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.jzy.gulimall.order.config.AlipayConfig;
import com.jzy.gulimall.order.service.OrderService;
import com.jzy.gulimall.order.vo.PayAsyncVo;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jzy
 * @date 2020/9/23 12:01
 */
@RestController
public class OrderPayedListener {

    @Resource
    private OrderService orderService;

    @Resource
    private AlipayConfig alipayConfig;
    /**
     * aiPay支付
     * 异步回调 验证签名
     */
    @PostMapping("/payed/notify")
    public String handlerAliPayed(PayAsyncVo payAsyncVo, HttpServletRequest request) throws AlipayApiException {
        //支付成功,修改订单状态,验证签名
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, String> params = new HashMap<>();
        for (String name : parameterMap.keySet()) {
            String[] values = parameterMap.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        boolean signVerify = AlipaySignature.certVerifyV1(params, alipayConfig.getAlipayCertPath(), alipayConfig.getCharset(), alipayConfig.getSignType());
        if (signVerify) {
            return orderService.handlerAliPayed(payAsyncVo);
        } else {
            return "error";
        }
    }
}
